package cn.highset.modules.base.controller.api;

import cn.highset.base.ApiBaseController;
import cn.highset.common.annotation.IgnoreAuth;
import cn.highset.common.utils.CommonUtil;
import cn.highset.common.utils.PageUtil;
import cn.highset.common.utils.ResultUtil;
import cn.highset.common.utils.SecurityUtil;
import cn.highset.common.vo.PageVo;
import cn.highset.common.vo.Result;
import cn.highset.common.vo.SearchVo;
import cn.highset.modules.base.entity.Activity;
import cn.highset.modules.base.entity.ActivityCollect;
import cn.highset.modules.base.service.ActivityCollectService;
import cn.highset.modules.base.service.ActivityService;
import cn.highset.modules.base.service.mybatis.IActivityCollectService;
import cn.highset.modules.base.service.mybatis.IActivityService;
import cn.highset.redis.client.RedisClient;
import cn.hutool.core.collection.CollUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Set;

/**
 * 类 描 述：API 小程序活动
 * 创建时间：2019-06-15 10:32
 * 创 建 人：victor
 */
@Slf4j
@RestController
@Api(description = "API活动信息")
@RequestMapping("/api/activity")
@Transactional
public class ApiActivityController extends ApiBaseController {

    @Autowired
    private ActivityService activityService;


    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private SecurityUtil securityUtil;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private ActivityCollectService activityCollectService;
    @Autowired
    private IActivityCollectService iActivityCollectService;
    @Autowired
    private IActivityService iActivityService;

    @ApiOperation(value = "获取活动列表")
    @IgnoreAuth
    @PostMapping("list")
    public Result<Page<Activity>> list(@ModelAttribute Activity activity, @ModelAttribute SearchVo searchVo,
                                       @ModelAttribute PageVo pageVo) {

        Page<Activity> page = activityService.findByCondition(activity, searchVo, PageUtil.initPage(pageVo));
        SimpleDateFormat monthEnSdf = new SimpleDateFormat("MMM dd", Locale.UK);
        SimpleDateFormat monthSdf = new SimpleDateFormat("MM月dd日", Locale.UK);
        page.getContent().forEach(e -> {
            e.setStartDateEn(monthEnSdf.format(e.getTimeStart()));
            e.setStartDate(monthSdf.format(e.getTimeStart()));
            entityManager.clear();
        });
        return new ResultUtil<Page<Activity>>().setData(page);
    }


    @ApiOperation(value = "获取活动详细信息")
    @IgnoreAuth
    @PostMapping("detail/{id}")
    public Result<Activity> detail(@PathVariable String id) {

        Activity activity = activityService.findById(id);
        activity.setDate(CommonUtil.getShowDate(activity.getTimeStart(), activity.getTimeEnd(),activity.getShowTime()));
        activity.setDateEn(CommonUtil.getShowDateEn(activity.getTimeStart(), activity.getTimeEnd(),activity.getShowTime()));
        return new ResultUtil<Activity>().setData(activity);
    }


    @ApiOperation(value = "收藏活动")
    @PostMapping("collect/{activityId}")
    public Result<Object> collect(@PathVariable String activityId) {

        String userid = securityUtil.getCurrUser().getId();
        if (activityCollectService.findByActivityIdAndUserid(activityId, userid) == null) {
            ActivityCollect activityCollect = new ActivityCollect();
            activityCollect.setActivityId(activityId);
            activityCollect.setUserid(userid);
            activityCollectService.save(activityCollect);
            iActivityService.incrCollectCount(activityId);
            String key = "activityCollect::" + userid;
            redisClient.set().sAdd(key, activityId);
        }
        return new ResultUtil<Object>().setSuccessMsg("收藏成功");
    }

    @ApiOperation(value = "取消收藏活动")
    @PostMapping("collectCancel/{activityId}")
    public Result<Object> collectCancel(@PathVariable String activityId) {

        String userid = securityUtil.getCurrUser().getId();
        ActivityCollect activityCollect = activityCollectService.findByActivityIdAndUserid(activityId, userid);
        if (activityCollect != null) {
            activityCollectService.delete(activityCollect.getId());
            iActivityService.dimCollectCount(activityId);
            String key = "activityCollect::" + userid;
            redisClient.set().remove(key, activityId);

        }
        return new ResultUtil<Object>().setSuccessMsg("取消收藏成功");
    }

    @ApiOperation(value = "获取收藏活动ID集合")
    @PostMapping("getCollect")
    public Result<Object> getCollect() {

        String userid = securityUtil.getCurrUser().getId();
        String key = "activityCollect::" + userid;
        Set<Object> set = redisClient.set().sMembers(key);
        if (set == null || CollUtil.isEmpty(set)) {
            Set<String> activityIds = iActivityCollectService.findActivityIdByUserid(userid);
            if (CollUtil.isNotEmpty(activityIds)) {
                redisClient.set().sAdd(key, activityIds.toArray());
            }
            return new ResultUtil<Object>().setData(activityIds);
        }

        return new ResultUtil<Object>().setData(set);
    }


    @ApiOperation(value = "获取用户收藏活动列表")
    @PostMapping("collectList")
    public Result<com.baomidou.mybatisplus.extension.plugins.pagination.Page<Activity>> collectList(
                                       @ModelAttribute PageVo pageVo) {
        String userid = securityUtil.getCurrUser().getId();
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Activity> page = iActivityService.getCollectListByUserid(PageUtil.initMpPage(pageVo),userid);
        SimpleDateFormat monthEnSdf = new SimpleDateFormat("MMM dd", Locale.UK);
        SimpleDateFormat monthSdf = new SimpleDateFormat("MM月dd日", Locale.UK);
        page.getRecords().forEach(e -> {
            e.setStartDateEn(monthEnSdf.format(e.getTimeStart()));
            e.setStartDate(monthSdf.format(e.getTimeStart()));
            entityManager.clear();
        });
        return new ResultUtil<com.baomidou.mybatisplus.extension.plugins.pagination.Page<Activity>>().setData(page);
    }

}
